
package jvm;

import java.io.*;
import java.lang.reflect.Method;

/**
 * @Author: liuchengcheng
 * @Date: 2021/8/5 9:57
 */
public class HelloClassLoader extends  ClassLoader{

    public static void main(String[] args) throws Exception {
        Class<?> hello = new HelloClassLoader().findClass("Hello");
        Method[] methods = hello.getDeclaredMethods();
        Method method = hello.getMethod("hello", null);
        Object obj = hello.newInstance();
        method.invoke(obj,null);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] content = getContent("F:\\code\\web\\study_01\\src\\jvm\\Hello.xlass");
        for (int i = 0; i < content.length; i++) {
            content[i] = (byte)(255 - content[i]);
        }
        /*OutputStream out = null;
        try{
            out = new FileOutputStream("F:\\code\\web\\study_01\\src\\jvm\\Hello.class");
            for (int i = 0; i < content.length; i++) {
                out.write(content[i]);
            }
            out.close();
        }catch (IOException e){
            System.out.println("将字节码写入文件！");
        }*/
        return defineClass(name,content,0,content.length);
    }

    public static byte[] getContent(String filePath) {
        File file = new File(filePath);
        FileInputStream fileInputStream = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            fileInputStream = new FileInputStream(file);
            byte[] b = new byte[1024];
            byte[] buffer = null;
            int len;
            while ((len = fileInputStream.read(b)) != -1){
                bos.write(b,0,len);
            }
            buffer = bos.toByteArray();
            return buffer;
        }catch (IOException e){
            System.out.println("===》读取文件出错！");
        }finally {
            try {
                fileInputStream.close();
                bos.close();
            }catch (IOException e){
                System.out.println("===》关闭资源出错！");
            }
        }
        return null;
    }
}
